{% extends "base.html" %}

{% block title %}个人资料{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h4 class="mb-0"><i class="fas fa-user-circle me-2"></i>个人资料</h4>
            <span class="badge bg-success rounded-pill">
                <i class="fas fa-check me-1"></i>已验证
            </span>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-4 text-center">
                    <div class="mb-3">
                        <img src="{{ current_user.avatar_url or 'https://via.placeholder.com/150' }}"
                             class="rounded-circle img-thumbnail" alt="用户头像"
                             style="width: 150px; height: 150px;">
                    </div>
                    <button class="btn btn-outline-primary btn-sm">
                        <i class="fas fa-camera me-1"></i>更换头像
                    </button>
                </div>
                <div class="col-md-8">
                    <div class="mb-3">
                        <label class="form-label fw-bold">用户名</label>
                        <p class="form-control bg-light">{{ current_user.username }}</p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">用户类型</label>
                        <p class="form-control bg-light">{{ '管理员' if current_user.is_admin else '普通用户' }}</p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">注册日期</label>
                        <p class="form-control bg-light">{{ current_user.created_at.strftime('%Y-%m-%d') if current_user.created_at else '未知' }}</p>
                    </div>
                </div>
            </div>

            <div class="d-flex justify-content-between mt-4">
                <a href="#" class="btn btn-outline-primary">
                    <i class="fas fa-edit me-1"></i>编辑资料
                </a>
                <a href="{{ url_for('auth.logout') }}" class="btn btn-danger">
                    <i class="fas fa-sign-out-alt me-1"></i>退出登录
                </a>
            </div>
        </div>
    </div>

    <!-- 已借阅书籍列表 -->
    <div class="card mt-4">
        <div class="card-header bg-light d-flex justify-content-between align-items-center">
            <h4 class="mb-0"><i class="fas fa-book me-2"></i>我的借阅记录</h4>
            <button class="btn btn-sm btn-outline-secondary" onclick="refreshBorrowedBooks()">
                <i class="fas fa-sync-alt me-1"></i>刷新
            </button>
        </div>
        <div class="card-body" id="borrowed-books">
            <div class="text-center py-4">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
                <p class="mt-2">正在加载借阅记录...</p>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    loadBorrowedBooks();
});

function refreshBorrowedBooks() {
    const container = document.getElementById('borrowed-books');
    container.innerHTML = `
        <div class="text-center py-4">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-2">正在刷新数据...</p>
        </div>`;
    loadBorrowedBooks();
}

function loadBorrowedBooks() {
    fetch('/book/borrowed', {
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => {
        if (response.status === 401) {
            window.location.href = '/login';
            return Promise.reject('请先登录');
        }
        if (!response.ok) {
            return response.json().then(err => Promise.reject(err.message || '获取借阅记录失败'));
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            renderBorrowedBooks(data.data);
        } else {
            showError(data.message || '获取借阅记录失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showError(typeof error === 'string' ? error : '加载借阅记录失败');
    });
}

function renderBorrowedBooks(records) {
    const container = document.getElementById('borrowed-books');

    if (!records || records.length === 0) {
        container.innerHTML = `
            <div class="text-center py-4">
                <i class="fas fa-book-open fa-3x text-muted mb-3"></i>
                <p class="text-muted">您当前没有借阅任何书籍</p>
            </div>`;
        return;
    }

    let html = `
    <div class="table-responsive">
        <table class="table table-hover align-middle">
            <thead class="table-light">
                <tr>
                    <th>书名</th>
                    <th>作者</th>
                    <th>封面</th>
                    <th>借阅日期</th>
                    <th>应还日期</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>`;

    records.forEach(record => {
        const dueDate = record.due_date ? new Date(record.due_date) : null;
        const borrowDate = record.borrow_date ? new Date(record.borrow_date) : null;
        const isOverdue = dueDate && dueDate < new Date();
        const isReturning = record.status === 'returning';

        html += `
        <tr>
            <td>${record.title || '无标题'}</td>
            <td>${record.author || '未知作者'}</td>
            <td><img src="${record.cover_image || 'https://via.placeholder.com/50'}"
                    style="height: 50px;" alt="封面"></td>
            <td>${borrowDate ? borrowDate.toLocaleDateString() : '未知'}</td>
            <td class="${isOverdue ? 'text-danger fw-bold' : ''}">
                ${dueDate ? dueDate.toLocaleDateString() : '未设置'}
            </td>
            <td>
                <span class="badge ${isReturning ? 'bg-warning' :
                    isOverdue ? 'bg-danger' :
                    record.status === 'returned' ? 'bg-success' : 'bg-primary'}">
                    ${isReturning ? '归还中' :
                    isOverdue ? '已逾期' :
                    record.status === 'returned' ? '已归还' : '借阅中'}
                </span>
            </td>
            <td>
                <button class="btn btn-sm btn-outline-primary"
                        onclick="viewBookDetail(${record.book_id})">
                    <i class="fas fa-info-circle"></i> 详情
                </button>
                ${(record.status === 'borrowed' || isReturning) ? `
                <button class="btn btn-sm ${isReturning ? 'btn-outline-secondary' : 'btn-outline-success'} ms-2"
                        ${isReturning ? 'disabled' : ''}
                        onclick="${isReturning ? '' : `returnBook(${record.id})`}">
                    <i class="fas fa-undo"></i>
                    ${isReturning ? '处理中...' : '归还'}
                </button>
                ` : ''}
            </td>
        </tr>`;
    });

    html += `</tbody></table></div>`;
    container.innerHTML = html;
}

function viewBookDetail(bookId) {
    window.location.href = `/book/books/${bookId}`;
}

function returnBook(recordId) {
    // 添加立即反馈
    const btn = event.target;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 提交中';

    fetch('/book/return/request', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ recordId: recordId })
    })
    .then(response => {
        if (!response.ok) throw new Error('网络错误');
        return response.json();
    })
    .then(data => {
        if (data.success) {
            // 关键修改：不直接刷新，先更新UI
            const row = btn.closest('tr');
            row.querySelector('.badge').className = 'badge bg-warning';
            row.querySelector('.badge').textContent = '归还中';
            btn.innerHTML = '<i class="fas fa-check"></i> 已申请';
        } else {
            throw new Error(data.message);
        }
    })
    .catch(error => {
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-undo"></i> 归还';
        alert(`错误: ${error.message}`);
    });
}

function showError(message) {
    document.getElementById('borrowed-books').innerHTML = `
        <div class="alert alert-danger">
            <i class="fas fa-exclamation-circle me-2"></i>
            ${message}
            <button class="btn btn-sm btn-outline-danger float-end"
                    onclick="loadBorrowedBooks()">
                重试
            </button>
        </div>`;
}
</script>

<style>
    .card {
        transition: transform 0.2s ease, box-shadow 0.2s ease;
        margin-bottom: 20px;
    }
    .card:hover {
        transform: translateY(-3px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    }
    .table th {
        white-space: nowrap;
    }
    .badge {
        font-weight: normal;
    }
    img {
        object-fit: cover;
    }
    .bg-warning {
        background-color: #ffc107 !important;
    }
</style>
{% endblock %}
